<!-- 右键菜单 -->
<template>
  <div ref="homeRef" class="main" @contextmenu.prevent="openMenu($event)">
    <MyMenu ref="MyMenuRef" :show="isShow" :data-list="dataList" :menu-top="menuTop" :menu-left="menuLeft"></MyMenu>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import MyMenu from './components/MyMenu.vue';

type dataListType = {
  icon: string;
  icon_type: string;
  name: string;
  callback: (arg1: string) => void;
  children?: dataListType[];
};

const homeRef = ref<HTMLElement | null>(null);
const MyMenuRef = ref<any>(null);

const isShow = ref<boolean>(false);
const dataList = ref<dataListType[]>([
  {
    icon: 'https://api.iconify.design/bi:moon-stars-fill.svg?color=currentColor',
    icon_type: 'url',
    name: '菜单1',
    callback: function () {
      console.log('点击了菜单1');
    },
    children: [
      {
        icon: 'https://api.iconify.design/bi:slash-circle.svg?color=currentColor',
        icon_type: 'url',
        name: '子菜单1',
        callback: function () {
          console.log('点击了子菜单1');
        },
      },
      {
        icon: 'https://api.iconify.design/bi:trash-fill.svg?color=currentColor',
        icon_type: 'url',
        name: '子菜单2',
        callback: function () {
          console.log('点击了子菜单2');
        },
      },
    ],
  },
  {
    icon: 'example.svg',
    icon_type: 'svg',
    name: '菜单2',
    callback: function () {
      console.log('点击了菜单2');
    },
  },
  {
    icon: 'exampleClose.png',
    icon_type: 'img',
    name: '关闭菜单',
    callback: function () {
      /* 此处需要编写关闭菜单的代码 */
      closeMenu();
    },
  },
]);

// 鼠标点击位置 x
const menuLeft = ref<number>(0);
// 鼠标点击位置 y
const menuTop = ref<number>(0);
const openMenu = (e: any) => {
  menuLeft.value = e.clientX;
  menuTop.value = e.clientY;
  isShow.value = true;
};

const bodyClick = (e: any) => {
  if (MyMenuRef.value && !MyMenuRef.value.menuRef.contains(e.target)) {
    closeMenu();
  }
};

const closeMenu = () => {
  isShow.value = false;
};

onMounted(() => {
  // 屏蔽浏览器自带的右键菜单
  if (homeRef.value) {
    homeRef.value.oncontextmenu = function () {
      return false;
    };
  }
  window.addEventListener('click', bodyClick);
});
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: $bg;
}
.custom-menu {
  // border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  width: 150px;
  // background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  z-index: 9999;
  color: #ffffff;
  background-image: url('@/assets/images/line-bg.png');
  background-repeat: no-repeat;
  background-size: 150px 100%;

  .custom-menu-item {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    border-bottom: 1px solid rgba(79, 133, 168, 1);
    &:hover {
      cursor: pointer;
      background-color: rgba(6, 53, 122, 0.8);
    }
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
